// FRAOZO - 3b
// contains the definiton of the grid class

#include <iostream>
#include <fstream>
#include <string>
#include <string.h>
#include <stdlib.h>
#include "d_matrix.h"
#include "d_except.h"


class grid
{
  public:
   grid ();
   void readInputFile(const string &fileName);
   void printGrid() const;
   int getRows() const;
   int getCols() const;
   char indexGrid (int row, int col) const;
   
  private:
   matrix<char> letterMatrix;
   int rows, columns;
   void getFileDims(char* line);
   void loadLetters(char* line, const int row, const int columns);

};

grid::grid()
:letterMatrix()
{
   //see d_matrix.h - defaults to 1x1 matrix
   rows=letterMatrix.rows();
   columns=letterMatrix.cols();
}

void grid::printGrid() const
//Print the contents of the private matrix
// in same format as inputxx files
{
   //iterate rows
   for (int rIdx=0; rIdx<getRows(); rIdx++)
   {

      //iterate columns
      for (int cIdx=0; cIdx<columns; cIdx++)
	 std::cout << letterMatrix[rIdx][cIdx] << " ";

      std::cout << endl;
   }

}

void grid::getFileDims(char* line)
//Passed the first line of the inputxx file, which contains
// <rows> <columns>
{
   //Split line with space token
   char *tokPos;

   //first split portion is the # of rows
   tokPos = strtok (line, " ");
   rows = atoi(tokPos);

   //second split portion is the # of columns
   tokPos = strtok (NULL, " ");
   columns = atoi(tokPos);

}
   
void grid::readInputFile(const string &fileName)
//Passed the file name.  Reads the file if possible.
//Calls getFileDims for the first line, then for every
//other line places the contents into the letterMatrix
{
   ifstream inputFile;
   inputFile.open(fileName.c_str());
  
   //First line is a buffer of chars
   char buffer[2048];
 
   if (!inputFile)
      throw (baseException ("Can't open grid file"));

   inputFile.getline(buffer, 2048);
   getFileDims(buffer);

   //Now the dimensions are know, resize the matrix accordingly
   letterMatrix.resize(getRows(), getCols());

   //load letters into matrix
   char letter;
   int currentRow=0;
   int currentCol=0;

   while (inputFile >> letter)
   {
      letterMatrix[currentRow][currentCol] = letter;

      if (currentCol < columns - 1)
	 currentCol++;
      else
      {
	 currentRow++;
	 currentCol = 0;
      }
   }

   inputFile.close();

}

int grid::getRows() const
{
   return rows;
}

int grid::getCols() const
{
   return columns;
}

char grid::indexGrid (int row, int col) const
{
   return letterMatrix[row][col];
}

